// pages/xgdeta/xgdeta.js
const app = getApp();
const url = app.globalData.url;
const common = require("../../utils/common.js");
const ImgLoader = require('../../template/img-loader/img-loader.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loding: true,
    xgewm:false,
    tps: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (o) {
    console.log(o);
    if(o.id){
      this.setData({id:o.id});
      this.imgLoader = new ImgLoader(this, this.imageOnLoad.bind(this))
      this.peizi();
    }else{
      this.setData({loding:false})
      wx.showModal({
        title: "提示",
        content: "数据出错",
        showCancel: false,//是否显示取消按钮
        // cancelText: btn[0],//默认是“确定”
        confirmText: "确定",//默认是“确定”
        success: function (res) {
          if (res.cancel) {
            //点击取消,默认隐藏弹框
            // if (options.finish) {
            // }
          } else {
            wx.navigateBack({ 
              delta: 1 ,
              fail(){
                wx.redirectTo({
                  url: "/pages/index/index"
                })
              }
            })
          }
        },
        fail: function (res) { },//接口调用失败的回调函数
        complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
      })
    }
  },
  // 配置文件
  peizi: function () {
    let that = this;
    app.fetch('api/wx/getpeizi', { dlx: 'xcxadd' }, "GET", (err, data) => {
      console.log(data)
      if (data.code == 200) {
        wx.setNavigationBarTitle({
          title: data.data.xcxadd.title.txt
        });
        that.setData({
          peizi: data.data,
          "addData.jb": 0,
          "addData.ll": data.data.xcxadd.qsll.txt,
          xgewm: data.data.xcxadd.xgewm.txt>0?false:true
        });
        that.hquser();
        that.hqxq();
      } else {
        wx.showModal({
          title: '接口数据错误',
          content: '接口:"' + url + 'api/wx/getpeizi.php' + '",msg:' + data.msg,
          showCancel: false,//是否显示取消按钮
          confirmText: "好的",//默认是“确定”
          confirmColor: 'skyblue',//确定文字的颜色
          success: function (res) {

          },
          fail: function (res) { },//接口调用失败的回调函数
          complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
        })
      }
    })
  },
  // 获取user信息;
  hquser() {
    let that = this;
    wx.getStorage({
      key: 'openid',
      success(res) {
        app.fetch('api/wx/user', { openid: res.data }, "POST", (err, data) => {
          if (data.code == 200) {
            that.setData({ user: data.data[0], "addData.uid": data.data[0].uid })
            // that.getcsData();
            
          }
        })
      },
      fail() {
        wx.showModal({
          title: '提示',
          content: '请先登录',
          success(res) {
            if (res.cancel) {
              //点击取消,默认隐藏弹框
              // if (options.finish) {
              wx.navigateBack({ delta: 1 })
              // }
            } else {
              wx.redirectTo({
                url: "/pages/my/my"
              })
            }
          }
        })
      }
    })
  },
  xgsf(){
    let that=this;
    let pz = that.data.peizi;
    let user = that.data.user;
    wx.showModal({
      title: '提示',
      content: '修改二维码将支付:' + pz.xcxadd.xgewm.txt +" 个 "+pz.xcx.jb.txt+",支付成功后,退出此页面将重新支付.",
      success(res) {
        if (res.cancel) {
          //点击取消,默认隐藏弹框
          // if (options.finish) {
          // wx.navigateBack({ delta: 1 })
          // }
        } else {
          if (user.jb - pz.xcxadd.xgewm.txt>=0){
            var tt = '修改二维码消耗了' + pz.xcxadd.xgewm.txt + "个" + that.data.peizi.xcx.jb.txt;
            that.czjb(2, pz.xcxadd.xgewm.txt, tt, "修改二维码消耗了");
            that.setData({ xgewm:true});
            that.addimgewm();
          }else{
            wx.showModal({
              title: pz.xcx.jb.txt+'不足',
              content: '当前只有 '+user.jb +" 个 " + pz.xcx.jb.txt ,
              showCancel: false,
              success(res) {}
            })
          }
        }
      }
    })
  },
  govip() {
    this.showtt("提示", "非会员无法设置,请开通会员后设置", ["等一会", "开会员"], 'bfh');
  },
  // 标题输入
  titleinput(e) {
    this.setData({
      "addData.title": e.detail.value
    })
  },
  // 平台输入
  ptnameinput(e) {
    this.setData({
      "addData.ptname": e.detail.value
    })
  },
  // 内容输入
  datalrinput(e) {
    this.setData({
      "addData.datalr": e.detail.value
    })
  },
  // 上传logo图片
  addimglogo() {
    let that = this;
    let num = that.data.peizi.xcxadd.logos.txt - that.data.imgList.length;
    if (num > 0) {
      wx.chooseImage({
        count: num,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: function (res) {
          var img = res.tempFilePaths;
          for (let p of img) {
            that.upload(p, 'logo');
            console.log(p)
          }
        },
        fail: function (res) { },
        complete: function (res) { },
      })
    } else {
      wx.showToast({
        title: '一次最多' + that.data.peizi.xcxadd.logos.txt + '张图片',//提示文字
        duration: 1000,//显示时长
        mask: false,//是否显示透明蒙层，防止触摸穿透，默认：false  
        image: '../../img/ico/clear.png', //图标，支持"success"、"loading"  
      })
    }
  },
  // 上传二维码图片
  addimgewm() {
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var img = res.tempFilePaths;
        for (let p of img) {
          that.upload(p, 'ewm');
          console.log(p)
        }
      },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  // 上传图片
  upload: function (img, lx) {
    wx.showToast({
      icon: "loading",
      title: "上传图片中..."
    });
    let that = this;
    wx.uploadFile({
      url: url + 'img/sctp.php', //接口
      filePath: img,
      name: 'file',
      formData: {
        'user': that.data.user.uid,
        lx: lx
      },
      success: function (res) {
        var data = res.data;
        if (!data.code) {
          data = JSON.parse(data);
        }
        console.log(res)
        if (data.code == 200) {
          if (lx == 'ewm') {
            var ewm = that.data.addData.ewm;
            if (ewm) {
              ewm = ewm.substring(ewm.indexOf('img') + 4);
              that.delsc(ewm);
            }
            that.setData({ "addData.ewm": url + data.uptp, tps:true, })
          }
          if (lx == 'logo') {
            let imgList = that.data.imgList;
            let img = url + data.ystp;
            let img1 = url + data.uptp;
            let imgList1 = { url: img1, ys: img, loaded: false };
            imgList.push(imgList1);
            that.setData({ imgList: imgList });
            that.loadImages();
          }
        }
        //do something
      },
      fail: function (error) {
        console.log(error);
      }
    })
  },
  //删除图片
  clearimg: function (e) {
    wx.showLoading({
      title: '删除中...',
    })
    let that = this;
    let i = e.currentTarget.dataset.index;
    let tpList = this.data.tpList;
    let imgList = this.data.imgList;
    let tp = [];
    let delimg = imgList[i].ys.substring(imgList[i].ys.indexOf('img') + 4);
    console.log(delimg)
    wx.request({
      url: url + 'img/deltp.php', //接口地址
      data: {
        img: delimg
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded" // 默认值
      },
      success(res) {
        console.log(res)
        if (res.data.code == 200) {
          let del = 'uptp/' + delimg.substring(delimg.indexOf('ystp') + 5);
          wx.request({
            url: url + 'img/deltp.php', //接口地址
            data: {
              img: del
            },
            method: "POST",
            header: {
              "Content-Type": "application/x-www-form-urlencoded" // 默认值
            },
            success(res) {
              console.log(res)
              if (res.data.code == 200) {
                for (let p of imgList) {
                  console.log(p)
                  if (p.url != imgList[i].url) {
                    console.log(p)
                    tp.push(p);
                  }
                  that.setData({ imgList: tp })
                }

              } else {
                wx.showModal({
                  title: '失败',
                  content: res.data,
                  showCancel: false,//是否显示取消按钮
                  cancelText: "否",//默认是“取消”
                  cancelColor: 'skyblue',//取消文字的颜色
                  confirmText: "是",//默认是“确定”
                  confirmColor: 'skyblue',//确定文字的颜色
                  success: function (res) {
                  },
                  fail: function (res) { },//接口调用失败的回调函数
                  complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
                })
              }
              wx.hideLoading()
            }
          })
        } else {
          wx.showModal({
            title: '失败',
            content: res.data,
            showCancel: false,//是否显示取消按钮
            cancelText: "否",//默认是“取消”
            cancelColor: 'skyblue',//取消文字的颜色
            confirmText: "是",//默认是“确定”
            confirmColor: 'skyblue',//确定文字的颜色
            success: function (res) {
            },
            fail: function (res) { },//接口调用失败的回调函数
            complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
          })
        }
        wx.hideLoading()
      }
    })
  },
  // 执行删除
  delsc: function (img) {
    let that = this;
    wx.request({
      url: url + 'img/deltp.php', //接口地址
      data: {
        img: img
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded" // 默认值
      },
      success(res) {
        console.log(res)
      }
    })
  },
  loadImages() {
    //同时发起全部图片的加载 
    console.log(1)
    this.data.imgList.forEach(item => {
      this.imgLoader.load(item.url)
    })
  },
  //加载完成后的回调
  imageOnLoad(err, data) {
    console.log('图片加载完成', err, data.src)

    const imgList = this.data.imgList.map(item => {
      if (item.url == data.src)
        item.loaded = true
      return item
    })
    this.setData({ imgList })
  },
  czjb(sz, jb, tt, xlx) {
    let that = this;
    let sj = {
      uid: that.data.user.uid,
      sz: sz,
      jb: jb,
      tt: tt,
      lx: 'xcx',
      xlx: xlx ? xlx : ''
    };
    app.fetch('api/wx/czjb', sj, "POST", (err, data) => {
      console.log(data)
      if (data.code == 200) {
        // that.hquser();
      }
    })
  },
  fbbtn() {
    let that = this;
    let adddata = that.data.addData;
    let img = that.data.imgList;
    adddata.vip = that.data.user.vip;
    adddata.issh = 2;
    var imgs = '';
    var ysimgs = '';
    for (var p of img) {
      imgs += p.url.substring(p.url.indexOf('img')) + ',';
      ysimgs += p.ys.substring(p.ys.indexOf('img')) + ",";
    }
    adddata.logolist = imgs.substring(0, imgs.length - 1);
    adddata.logoyslist = ysimgs.substring(0, ysimgs.length - 1);
    adddata.ewm = adddata.ewm.substring(adddata.ewm.indexOf('img'));
    console.log(adddata);
    app.fetch('api/wx/upxq', { data: JSON.stringify(adddata),did:that.data.id,uid:that.data.user.uid,uname:that.data.user.nickName }, "POST", (err, data) => {
      console.log(data)
      if (data.code == 200) {
        that.setData({ tps: false});
        var tt = "修改成功";
        wx.showToast({
          title: tt,
          icon: 'success',
          duration: 1000
        });
        setTimeout(function () {
            wx.navigateBack({
              data: 1
            })
          
        }, 1000)
      } else {
        that.setData({ addData: {}, imgList: [] });
        wx.showModal({
          title: '提示',
          content: data.code.msg,
        })
      }
    })
  },
  showtt(tt, msg, btn, fhm) {
    let that = this;
    wx.showModal({
      title: tt,
      content: msg,
      showCancel: true,//是否显示取消按钮
      cancelText: btn[0],//默认是“确定”
      confirmText: btn[1],//默认是“确定”
      success: function (res) {
        if (res.cancel) {
          //点击取消,默认隐藏弹框
          // if (options.finish) {
          if (!fhm) {
            wx.navigateBack({ delta: 1 })
          }
          // }
        } else {
          if (tt == '提示') {
            wx.redirectTo({
              url: "/pages/vip/vip"
            })
          } else {
            that.setData({ mzsm: true });
          }
        }
      },
      fail: function (res) { },//接口调用失败的回调函数
      complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
    })
  },
  tszlwtw() {
    wx.showModal({
      title: "提示",
      content: "资料未填完,请认真检查",
      showCancel: false,//是否显示取消按钮
      // cancelText: btn[0],//默认是“确定”
      confirmText: "确认",//默认是“确定”
      success: function (res) {

      },
      fail: function (res) { },//接口调用失败的回调函数
      complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
    })
  },
  // 跳转url
  tourl(e) {
    let url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: url
    })
  },
  //放大图片
  previewImage: function (e) {
    var src = e.currentTarget.dataset.src; //获取data-src
    var imgList = this.data.imgList; //获取data-list
    //要把对象中需要的键值对拿出来，放进一个数组，Object.keys是为了取到对象的长度进行遍历
    var imgArr = [];
    var objkeys = Object.keys(imgList);
    for (var i = 0; i < objkeys.length; i++) {
      imgArr.push(imgList[i].url);
    }
    //图片预览
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: imgArr // 需要预览的图片http链接列表
    })
  },
  // 设置主图
  swzt(e) {
    console.log(e)
    if (e.currentTarget.dataset.i != 0) {
      this.setData({ ztxs: e.currentTarget.dataset.i });
    }
  },
  quxzt() {
    this.setData({ ztxs: null })
  },
  szzts(e) {
    let data = this.data.imgList;
    let th = this.data.imgList[0];
    let src = e.currentTarget.dataset.src;
    let xb = 0;
    for (var j = 0; j < data.length; j++) {
      const item = data[j];
      if (item.url == src) {
        xb = j;
      }
    }
    if (xb != 0) {
      data[0] = data[xb];
      data[xb] = th;
      this.setData({ imgList: data });
      this.quxzt();
    }
  },
  pdt() {
    if (this.data.peizi.xcx.fhyaddsf.txt == 1 || this.data.user.vip == 2) {
    } else {
      this.govip();
    }
  },
  // 金币设置
  jb(e) {
    if (this.data.peizi.xcx.fhyaddsf.txt == 1 || this.data.user.vip == 2) {
      var vipsfb = e.detail.value - (e.detail.value * this.data.peizi.xcx.ptss.txt);
      vipsfb = vipsfb.toFixed(2);
      this.setData({ "addData.jb": e.detail.value, vipsfb: vipsfb });
    } else {
      this.setData({ "addData.jb": 0 });
    }
  },
  // 评论设置
  ispl(e) {
    this.setData({ "addData.ispl": e.detail.value ? 1 : 2 });
  },
  hqxq() {
    let that = this;
    let sj = {
      id: that.data.id,
      isqx: 3,
    };
    app.fetch('api/wx/getdetail', sj, "POST", (err, data) => {
      console.log(data)
      if (data.code == 200) {
        console.log(data);
        wx.setNavigationBarTitle({
          title:"修改-"+ data.dt.title
        });
        data.dt.uptp = data.dt.logolist.split(",");
        data.dt.ystp = data.dt.logoyslist.split(",");
        let imgList = [];
        for (let i = 0; i < data.dt.uptp.length; i++) {
          let imgList1 = { url: url + data.dt.uptp[i], ys: url + data.dt.ystp[i], loaded: false };
          imgList.push(imgList1);
        }
        data.dt.ewm = url + data.dt.ewm;
        var vipsfb = data.dt.jb - (data.dt.jb * that.data.peizi.xcx.ptss.txt);
        vipsfb = vipsfb.toFixed(2);
        data.dt.xgtime = common.format(data.dt.xgtime)
        data.dt.addtime = common.format(data.dt.addtime)
        that.setData({ addData: data.dt, imgList: imgList, loding: false, vipsfb: vipsfb});
        that.loadImages();
        // that.setData({ user: data.data[0] })
      } else if (data.code == 400) {
        wx.showModal({
          title: '提示',
          content: data.msg,
          showCancel: false,//是否显示取消按钮
          confirmText: "好的",//默认是“确定”
          confirmColor: 'skyblue',//确定文字的颜色
          success: function (res) {
            wx.navigateBack({
              data: 1,
              fail() {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            })
          },
        })
      } else {
        wx.showModal({
          title: '数据错误',
          content: '接口:"' + url + 'api/wx/getdetail' + '",msg:' + data.msg,
          showCancel: false,//是否显示取消按钮
          confirmText: "好的",//默认是“确定”
          confirmColor: 'skyblue',//确定文字的颜色
          success: function (res) {
            wx.navigateBack({
              data: 1,
              fail() {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            })
          },
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (this.data.tps){
      this.fbbtn();
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})